

import { cfw } from "../../cfw/cfw";
import { ResType } from "../../cfw/res/ResDefine";
import ResItem from "../../cfw/res/ResItem";
import { engine } from "../../engine/engine";
import { BehaviorTree } from "./BehaviorTree";
import { BehaviorTreeBuilderWithJson } from "./BehaviorTreeBuilderWithJson";

export class BehaviorTreeFactory {
    protected _path = "";

    private unitTreeMap: Map<number, BehaviorTree> = new Map<number, BehaviorTree>();

    constructor(p: string) {
        this._path = p;
    }

    hasUnitTree(unitId: number) {
        return this.unitTreeMap.has(unitId)
    }

    setUnitTree(unitUID: number, tree: BehaviorTree): void {
        if (this.unitTreeMap.has(unitUID)) {
            engine.error('tree is have uid is ', unitUID)
            return;
        }
        this.unitTreeMap.set(unitUID, tree);
    }

    addUnitTree(jsonName: string, bundleName: string, uid: number, target?: any) {
        let tree = this.buildTree(jsonName, bundleName, target)
        this.setUnitTree(uid, tree)
        return tree;
    }

    buildTree(jsonName: string, bundleName: string, target?: any) {
        let path = this._path + jsonName;
        let tree = this.createTree(path, bundleName, target)
        return tree;
    }

    createTree(path: string, bundleName: string, target?: any): BehaviorTree {
        let data: ResItem = cfw.loader.getRes(path, ResType.Json, bundleName);
        if (data) {
            let tree = BehaviorTreeBuilderWithJson.instance().buildTree(data.getRes().json, target)
            return tree;
        } else {
            engine.error(' 行为树创建失败 jsonName', path)
            return null;
        }
    }


    getTreeByName(className: string, path: string, bundleName: string, target: any): BehaviorTree {
        let data: ResItem = cfw.loader.getRes(path, ResType.Json, bundleName);
        if (data) {
            let tree = BehaviorTreeBuilderWithJson.instance().buildTreeByName(className, data.getRes().json, target)
            return tree;
        } else {
            engine.error(' 行为树创建失败 jsonName', path)
            return null;
        }

    }

    public getUnitTree(unitUID: number): BehaviorTree {
        let unitTree = this.unitTreeMap.get(unitUID);
        if (unitTree) {
            return unitTree;
        }
        return null;
    }
    /**
     * 删除指定单位
     * @param unitUID 
     */
    public deleteUnit(unitUID: number): void {
        this.unitTreeMap.delete(unitUID);
    }

    public clear(): void {
        this.unitTreeMap.clear();
    }
}